package org.siteanalyser.service.impl;

import org.siteanalyser.domain.AnalysisReport;
import org.siteanalyser.domain.Message;
import org.siteanalyser.service.Service;
import org.siteanalyser.service.SystemException;
import org.siteanalyser.util.HtmlParseUtil;
import org.springframework.beans.factory.annotation.Required;

import com.google.gson.Gson;
import com.seomoz.api.authentication.Authenticator;
import com.seomoz.api.response.UrlResponse;
import com.seomoz.api.service.URLMetricsService;

public class SeomozServiceImpl implements Service {
    private String secretKey;
    private String accessId;

    @Required
    public void setSecretKey(final String secretKey) {
        this.secretKey = secretKey;
    }

    @Required
    public void setAccessId(final String accessId) {
        this.accessId = accessId;
    }

    public void process(final Message message) throws SystemException {
        seomozReport(message.getRequest().getUrl(), message.getReport());
    }

    private void seomozReport(final String url, final AnalysisReport result) {
        final Authenticator authenticator = new Authenticator();
        authenticator.setAccessID(accessId);
        authenticator.setSecretKey(secretKey);

        final URLMetricsService urlMetricsService = new URLMetricsService(authenticator);
        final String response = urlMetricsService.getUrlMetrics(HtmlParseUtil.removeProtocol(url));
        final Gson gson = new Gson();
        final UrlResponse res = gson.fromJson(response, UrlResponse.class);
        result.addReportItem("seomozbacklinks", res.getUeid());
    }

}
